/**
 * 导入仓库 url方式
 * @param type 默认normal, retry：重新导入
 * @param projectInfo 默认为null，默认数据，在重新导入时用到
 * @param retryCallback 重新导入成功的回调
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Form, Input, Field, Balloon } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import exceed from 'utils/apimap';
import { encrypt } from 'utils/JSEncrypt';
import docs from 'utils/docs';
import ImportProjectListModal from 'components/importProjectListModal';
import AccountMessage from '../accountMessage';
import LoadingAccount from '../accountMessage/loading';
import track from 'utils/track';
import CONSTANTS from 'utils/constants.js';
import intl from '../../../locale';

const { PLATFORM_TYPES } = CONSTANTS;

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

export default class ImportProjectByUrlModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
    type: PropTypes.string,
    retryCallback: PropTypes.func,
    platform_type: PropTypes.string,
  };

  static defaultProps = {
    trigger: null,
    closeModal: () => {},
    type: 'normal', // 默认为normal, retry为重新导入
    retryCallback: () => {},
    platform_type: 'PRIVATE_GITLAB',
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      isFullScreenModalShow: false,
      accountInfo: {},
      isGetttingAccount: false,
      // 是否是刚绑定
      isFirst: false,
    };
  }

  componentDidMount() {
    this.getAccountInfo();
  }

  // 解绑后的操作
  handleUnbind = () => {
    this.getNewData();
  };

  getNewData = () => {
    this.setState(
      {
        isFullScreenModalShow: false,
        accountInfo: {},
        isGetttingAccount: false,
        // 是否是刚绑定
        isFirst: false,
      },
      () => {
        this.getAccountInfo();
      },
    );
  };

  getAccountInfo = () => {
    this.setState({
      isGetttingAccount: true,
    });

    this.props.setDisabled(true);
    exceed
      .fetch({
        api: 'projects.import.account.get',
        data: { platform_type: this.props.platform_type },
      })
      .then((result) => {
        this.setState({
          accountInfo: result,
          isFirst: false,
          isGetttingAccount: false,
        });

        this.props.setDisabled(false);
      })
      .fail((err) => {
        this.setState({
          isGetttingAccount: false,
        });

        this.props.setDisabled(false);
        console.error(err);
      });
  };

  gitValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (!/^((https|http)?:\/\/)[^\s]+/.test(value)) {
      callback(
        intl.get({
          id: 'code-assets.importProjectModal.privateGitLab.TheUrlOfTheCode',
          defaultMessage: '代码库地址请以 http://, https://开头',
        }),
      );
    } else if (
      !/^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*(\/)?$/.test(
        value,
      )
    ) {
      callback(
        intl.get({
          id: 'code-assets.importProjectModal.privateGitLab.EnterTheHomePageAddress',
          defaultMessage: '请输入自建 Gitlab 首页地址，如https://gitlab.com，非代码库完整URL',
        }),
      );
    } else {
      callback();
    }
  };

  handleOk = () => {
    const { accountInfo } = this.state;
    // 已绑定帐号直接打开弹窗
    if (Object.keys(accountInfo).length) {
      this.setState({
        isFullScreenModalShow: true,
      });

      return;
    }
    this.field.validate((errors) => {
      if (!errors) {
        if (this.props.submitting) {
          return;
        }
        this.props.setSubmitting(true);
        const formData = this.field.getValues();

        if (formData.token) {
          formData.token_encrypted_type = 'rsa'; // 使用加密
          formData.token = encrypt(formData.token, this.props.PUBLIC_KEY);
        } else {
          formData.token_encrypted_type = 'text';
        }

        const data = {
          platform_type: this.props.platform_type,
          platform_host: formData.platform_host,
          token: formData.token,
          token_encrypted_type: formData.token_encrypted_type,
          override: true,
        };

        this.formSubmit(data, () => {
          this.props.setSubmitting(false);
        });
      }
    });
  };

  formSubmit = (formData, cb) => {
    exceed
      .fetch({
        api: 'projects.import.account.post',
        data: formData,
      })
      .then((result) => {
        this.setState({
          isFullScreenModalShow: true,
          accountInfo: result,
          isFirst: true,
        });

        cb && cb();
      })
      .fail((err) => {
        cb && cb();
        console.error(err);
      });
  };

  unbindCallback = () => {
    this.setState({
      accountInfo: {},
      isFirst: false,
    });
  };

  render() {
    const { init } = this.field;
    const { isFullScreenModalShow, accountInfo, isGetttingAccount, isFirst } = this.state;
    const { platform_type } = this.props;
    // 是不是公有云gitlab
    const isGitlab = platform_type === 'GITLAB';
    // 是不是github
    const isGithub = platform_type === 'GITHUB';
    const isCoding = platform_type === 'CODING';
    if (isGetttingAccount) {
      return <LoadingAccount />;
    }

    return (
      <React.Fragment>
        {Object.keys(accountInfo).length ? (
          <AccountMessage accountInfo={accountInfo} unbindCallback={this.unbindCallback} />
        ) : (
          <Form {...formItemLayout} field={this.field} labelAlign="top">
            <FormItem
              label={'Host URL'}
              required
              style={{ display: isGitlab || isGithub || isCoding ? 'none' : 'block' }}
            >
              <Input
                autoFocus={!isGitlab && !isGithub && !isCoding}
                placeholder={intl.get({
                  id: 'code-assets.importProjectModal.privateGitLab.SuchAsHttpsGitlabMycompany',
                  defaultMessage: '如 https://gitlab.mycompany.com',
                })}
                {...init('platform_host', {
                  rules: [
                    {
                      required: true,
                      message: intl.get({
                        id: 'code-assets.importProjectModal.privateGitLab.ThisParameterIsRequired',
                        defaultMessage: '该项为必填项',
                      }),
                    },

                    {
                      validator: this.gitValidator,
                    },
                  ],

                  initValue: PLATFORM_TYPES[platform_type]
                    ? PLATFORM_TYPES[platform_type].host
                    : '',
                })}
              />
            </FormItem>
            <FormItem
              required
              label={
                <span>
                  <span className="before-icon-text">Access Token</span>
                  <Balloon
                    align="t"
                    trigger={<YunxiaoIcon type="question-line" className="access-token-help" />}
                    type="normal"
                    closable={false}
                  >
                    {intl.get({
                      id: 'code-assets.importProjectModal.privateGitLab.AccessTokenIsGeneratedFor',
                      defaultMessage: 'Access Token 生成，请参考',
                    })}

                    <a href={docs('accessTokenGenerated')} target="_blank" rel="noreferrer">
                      {intl.get({
                        id: 'code-assets.importProjectModal.privateGitLab.HelpDocumentation',
                        defaultMessage: '帮助文档',
                      })}
                    </a>
                  </Balloon>
                </span>
              }
            >
              <Input
                autoFocus-={isGitlab || isGithub || isCoding}
                placeholder={intl.get({
                  id: 'code-assets.importProjectModal.privateGitLab.SuchAsSfHnp',
                  defaultMessage: '如 67sf7648hnp',
                })}
                {...init('token', {
                  rules: [
                    {
                      required: true,
                      message: intl.get({
                        id: 'code-assets.importProjectModal.privateGitLab.ThisParameterIsRequired',
                        defaultMessage: '该项为必填项',
                      }),
                    },
                  ],

                  initValue: '',
                  props: {
                    onChange: () => {
                      let trackType = '';
                      if (isGithub) {
                        trackType = 'import github';
                      } else if (isGitlab) {
                        trackType = 'import gitlab';
                      } else if (isCoding) {
                        trackType = 'import coding';
                      } else {
                        trackType = 'import self-built gitlab';
                      }
                      track({
                        action: 'input_access_token',
                        page: 'Dialog-ImportRepo',
                        type: trackType,
                        control: '',
                      });
                    },
                  },
                })}
              />
            </FormItem>
          </Form>
        )}

        {isFullScreenModalShow ? (
          <ImportProjectListModal
            accountInfo={accountInfo}
            isFirst={isFirst}
            isModalOpen={isFullScreenModalShow}
            handleUnbind={this.handleUnbind}
            closeModal={() => {
              this.setState({
                isFullScreenModalShow: false,
                isFirst: false,
              });
            }}
          />
        ) : null}
      </React.Fragment>
    );
  }
}
